//
//  LBAnimation.m
//  Lottery360
//
//  Created by gujian on 16/3/9.
//  Copyright © 2016年 Qihoo. All rights reserved.
//

#import "LBAnimation.h"

static const CGFloat MINDURATION = 0.92;

@implementation LBAnimation

- (instancetype)init
{
    self = [super init];
    if (self) {
        
    }
    return self;
}

+ (instancetype)sharedInstance
{
    static dispatch_once_t pred;
    static LBAnimation *animation = nil;
    dispatch_once(&pred, ^{
        animation = [[LBAnimation alloc] init];
    });
    return animation;
}

- (void)dealloc
{
    LotLog(@"%@ life is end", [LBAnimation class]);
}

- (void)throwObject:(UIView *)targetView From:(CGPoint)beginPos To:(CGPoint)endPos
              Scale:(CGFloat)scale
{
    
    CGFloat distance = sqrtf((endPos.x - beginPos.x)*(endPos.x - beginPos.x) + (endPos.y-beginPos.y)*(endPos.y-beginPos.y));
    CGFloat totalDuration = (distance * 0.002) > MINDURATION? (distance * 0.002) : MINDURATION;
    CGFloat rotationDuration = 0.15;
    
    CGMutablePathRef path = CGPathCreateMutable();
    
    CGPathMoveToPoint(path, NULL, beginPos.x, beginPos.y);
    CGPathAddLineToPoint(path, NULL, endPos.x, endPos.y);
    
    CAKeyframeAnimation *posAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    posAnimation.path = path;
    CFRelease(path);
    
    CABasicAnimation *scaleAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    scaleAnimation.autoreverses = YES;
    scaleAnimation.toValue = @(scale);
    
    CABasicAnimation *rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotationAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    rotationAnimation.repeatCount = MAXFLOAT;
    rotationAnimation.cumulative = YES;
    rotationAnimation.duration = rotationDuration;
    rotationAnimation.fromValue = 0;
    rotationAnimation.toValue = [NSNumber numberWithFloat:M_PI];
    
    CAAnimationGroup *groupAnima = [CAAnimationGroup animation];
    groupAnima.delegate = self;
    groupAnima.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
    groupAnima.duration = totalDuration;
    groupAnima.removedOnCompletion = NO;
    groupAnima.fillMode = kCAFillModeForwards;
    groupAnima.repeatCount = 1;
    groupAnima.animations = @[rotationAnimation,posAnimation,scaleAnimation];
    [targetView.layer addAnimation:groupAnima forKey:@"position scale"];
    
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:totalDuration target:self selector:@selector(animationWillFinished:) userInfo:targetView repeats:NO];
    //避免当滑动UIScrollView时，动画停止
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
}

- (void)animationWillFinished:(NSTimer *)timer{
    UIView *animatedView = [timer userInfo];
    [timer invalidate];
    timer = nil;
    
    if ([_delegate respondsToSelector:@selector(lbAnimationWillFinished:)]) {
        [_delegate lbAnimationWillFinished:animatedView];
    }
}

- (CABasicAnimation *)animationWithObject:(UIView *)targetView Pos:(CGPoint)pos TimeOffset:(CGFloat)offset
{
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
    animation.cumulative = YES;
    animation.duration = 0.25;
    //保证停在最终位置
    animation.fillMode = kCAFillModeForwards;
    animation.removedOnCompletion = NO;
    animation.toValue =[NSValue valueWithCGPoint:pos];
    animation.beginTime = CACurrentMediaTime() + offset;
    
    return animation;
}

- (CAKeyframeAnimation *)keyAnimationObject:(UIView *)targetView Pos:(CGPoint)pos TimeOffset:(CGFloat)offset
{
    CAKeyframeAnimation *keyFrameAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    keyFrameAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
    keyFrameAnimation.cumulative = YES;
    keyFrameAnimation.duration = 1.0;
    keyFrameAnimation.fillMode = kCAFillModeForwards;
    keyFrameAnimation.removedOnCompletion = NO;
    keyFrameAnimation.beginTime = CACurrentMediaTime() + offset;
    
    NSValue *value0 = [NSValue valueWithCGPoint:CGPointMake(pos.x, SCREEN_HEIGHT)];
    NSValue *value1 = [NSValue valueWithCGPoint:CGPointMake(pos.x, pos.y-40)];
    NSValue *value2 = [NSValue valueWithCGPoint:pos];
    NSValue *value3 = [NSValue valueWithCGPoint:CGPointMake(pos.x, pos.y+5)];
    
    //
    keyFrameAnimation.values = @[value0,value2,value1,value2,value3,value2];
    
    return keyFrameAnimation;
}


#pragma mark - CAAnimationDelegate
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
    if ([_delegate respondsToSelector:@selector(lbAnimationDidStop:finished:)]) {
        [_delegate lbAnimationDidStop:anim finished:flag];
    }
}


@end
